<template>
  <div class="notice-users">
    <div class="card">
      <div class="btn-group" style="margin-bottom: 20px;">
        <el-button
          type="primary"
          @click="handleOpenDialog"
        >
          通知人设置
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column label="警告类型" align="center">
          <template v-slot="{ row }">
            {{ row?.type?.name }}
          </template>
        </el-table-column>

        <el-table-column
          label="人员"
          align="center"
          prop="user_list"
        >
          <template v-slot="{ row }">
            <el-popover
              placement="top-start"
              title="通知人"
              width="200"
              trigger="click"
            >
              <el-button
                slot="reference"
                type="text"
              >
                查看
              </el-button>
              <template>
                <div>
                  <el-tag
                    v-for="item in row.user_list"
                    :key="item.id"
                    style="margin: 0 10px 10px 0;"
                  >
                    {{ item.username }}
                  </el-tag>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column
          label="创建日期"
          align="center"
          prop="created_at"
        >
          <template v-slot="{ row }">
            {{ timeFormat(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              size="mini"
              @click="handleEditNoticeUsers(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <Pagination
          v-if="total"
          style="margin-top: 0; padding-bottom: 0;"
          :total="total"
          :limit="searchParam.paginate"
          :page="searchParam.page"
          @pagination="pagination"
        />
      </div>
    </div>

    <WithDialog
      :visible.sync="dialogVisible"
      width="300px"
      :title="formData.id ? '修改通知人' : '添加通知人'"
      :confirm-btn-loading="btnLoading"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <el-form
        ref="elFormRef"
        :model="formData"
        :rules="rules"
      >
        <el-form-item label="通知人" prop="user_list">
          <el-button
            type="text"
            @click="userSelectModalVisible = true"
          >
            {{ formData.user_list.length ? `已选择${formData.user_list.length}人` : '请选择通知人' }}
          </el-button>
        </el-form-item>

        <el-form-item label="警告类型">
          <el-select
            v-model="formData.type_id"
            clearable
          >
            <el-option
              v-for="(item, index) in warningType"
              :key="index"
              :value="item.value"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </WithDialog>

    <UserSelectModal
      v-model="formData.user_list"
      :visible.sync="userSelectModalVisible"
    />
  </div>
</template>
<script>
import { getWarningNoticeUsers, getWarningType, setWarningNoticeUsers } from '@/api/gps'
import WithDialog from '@/components/WithDialog/withDialog.vue'
import UserSelectModal from '@/components/UserSelectModal/UserSelectModal.vue'
import { isArray } from '@/utils/kris_utils'
import { timeFormat } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

export default {
  name: '',
  components: { Pagination, UserSelectModal, WithDialog },
  data() {
    return {
      loading: false,
      btnLoading: false,
      list: [],
      dialogVisible: false,
      formData: {
        id: null,
        user_list: [],
        type_id: null
      },
      warningType: [],
      userSelectModalVisible: false,
      rules: {
        user_list: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请选择通知人'))
              } else if (isArray(value) && value.length <= 0) {
                callback(new Error('请选择通知人'))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  created() {
    this.getNoticeUsers()
    this.getWarningType()
  },

  methods: {
    timeFormat,
    async getNoticeUsers() {
      this.loading = true
      try {
        const res = await getWarningNoticeUsers()
        this.list = res.data
      } catch (error) {
        this.$message.error(error?.response?.data.message || '获取通知用户失败')
      } finally {
        this.loading = false
      }
    },

    handleOpenDialog() {
      this.dialogVisible = true
    },

    async getWarningType() {
      try {
        const res = await getWarningType()
        this.warningType = res.data.map(item => {
          return {
            ...item,
            value: parseInt(item.value)
          }
        })
      } catch (error) {
        throw new Error(error?.response?.data.message || '获取警告类型失败')
      }
    },

    handleConfirm() {
      this.$refs.elFormRef.validate(valid => {
        if (!valid) return this.$message.error('请将信息填写完整')
        this.btnLoading = true
        const params = {
          ...this.formData,
          user_list: JSON.stringify(this.formData.user_list)
        }

        this.setWarningNoticeUsersFetch(params)
      })
    },

    async setWarningNoticeUsersFetch(data) {
      try {
        const res = await setWarningNoticeUsers(data)
        this.$message.success('通知人设置成功')
        this.handleCancel()
        this.getNoticeUsers()
      } catch (error) {
        this.$message.error(error?.response?.data.message || '通知人设置失败')
      } finally {
        this.btnLoading = false
      }
    },

    handleCancel() {
      this.dialogVisible = false
      this.formData = this.$options.data().formData
      this.$refs.elFormRef.resetFields()
    },

    handleEditNoticeUsers(row) {
      this.formData = {
        id: row.id,
        type_id: row.rail_mes_type_id,
        user_list: row.user_list.map(item => item.id)
      }

      this.dialogVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.notice-users {
  padding: 20px;
}
</style>
